package shoppingmall.reception.controller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import shoppingmall.reception.dto.LoginRequestParamsVO;
import shoppingmall.reception.dto.Result;

import java.util.HashMap;
import java.util.Map;

import shoppingmall.reception.pojo.User;
import shoppingmall.reception.service.SignInService;
import shoppingmall.reception.utils.JwtUtils;
/**
 * 前台会员用户登录 控制层
 */
@SuppressWarnings({"all"})
@Slf4j
@RestController
public class SignInController {
    //用户登录服务层接口实例
    @Autowired
    private SignInService signInService;

    /**
     * 前台会员用户登录(支持用户名+密码+验证码 和 手机号+密码+验证码 登录)
     */
    @PostMapping("/reception/login")
    public Result userLogin (@RequestBody LoginRequestParamsVO user, HttpServletRequest request) {
        log.info("前台会员用户登录,用户名={},手机号={},密码={},验证码={}",user.getUsername(),user.getPhone(),user.getPassword(),user.getCaptchaCode());
        //从会话中获取图片验证码
        String captchaImgCode = request.getSession().getAttribute("captchaCode").toString();
        if(!captchaImgCode.toLowerCase().equals(user.getCaptchaCode().toLowerCase())){
            return Result.error("验证码错误!");
        }
        //调用service层方法查询用户信息
        User userInfo = signInService.userLogin(user);
        //登录成功，生成令牌，下发令牌
        if(userInfo != null){
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",userInfo.getId());
            claims.put("username",userInfo.getUsername());
            String jwt = JwtUtils.generateJwt(claims);
            return Result.success(jwt);
        }
        return Result.error("用户名或密码错误!");
    }
}
